$(function () {
  // App.loadTop();

  var pageAllTotal = 0; //控制全部订单的总页数
  var state = "1";
  var check_state = "";
  var payType = "";

  App.loginOut();
  var userInfo = JSON.parse(localStorage.getItem("logInfo"));
  $(".top .userInfo").html(userInfo.login);

  //日期选择
  $(".orderForm .main_top .btn-group").on("click", "button", function () {
    $(this).addClass("active").siblings().removeClass("active");
  })

  //获取支付方式
  App.ajax("ss_wx/pay_methods", "post", {"search": true}, function (res) {
    if (res.flag == true) {
      var payHtml = "<option value='all'>全部</option>";
      $.each(res.info, function (i, v) {
        payHtml += "<option value='" + v.name + "' data-paytype='" + JSON.stringify(v) + "'>" + v.name + "</option>"
      })
      $(".payList select").html(payHtml);
    } else {
      App.msg(res.msg);
    }
    if (!res.TokenTrue) {
      App.msg("Token失效，即将跳转到登录页面", function () {
        setTimeout(function () {
          location.href = "../login.html";
        }, 1000)
      })
    }
  })
  getOrderDetails("1", "");
  //获取订单信息
  function getOrderDetails(state, check_state, payType) {
    if (state == 6) {
      App.ajax("ss_wx/pos_refund_details", "post", {}, function (res) {
        if (res.flag == true) {
          pageAllTotal = res.pageAllTotal;
          $('.M-box').pagination({
            pageCount: pageAllTotal,
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '<<',
            nextContent: '>>',
            count: 2,
            isHide: true,
            jumpBtn: "GO",
            callback: function (api) {
              console.log("refund===", api.getCurrent())
              pagination_refund_orders(api.getCurrent())
            }
          });

          var orderHtml = "";
          if (res.order_detail.length == 0) {
            orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
            $(".orderForm .tableData tbody").html(orderHtml);
          } else {
            if (payType) {
              res.order_detail = res.order_detail.filter(function (m) {
                //  m.pay_method.indexOf(payType)>-1
                m.pay_method = m.pay_method.filter(function (p) {
                  return p.pay_method == payType
                })
                return m.pay_method.length > 0
              })
            }
            fillData(res, orderHtml);
          }
        } else {
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    } else {
      App.ajax("ss_wx/order_details", "post", {
        state: state,
        check_state: check_state,
        payType: payType
      }, function (res) {
        console.log("order_details res======", res);
        if (res.flag == true) {
          pageAllTotal = res.pageAllTotal;
          $('.M-box').pagination({
            // totalData: 0,
            pageCount: pageAllTotal,
            // showData: 15,
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '<<',
            nextContent: '>>',
            count: 2,
            isHide: true,
            jumpBtn: "GO",
            callback: function (api) {
              pagination_orders(api.getCurrent())
            }
          });
          var orderHtml = "";
          if (res.order_detail.length == 0) {
            orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
            $(".orderForm .tableData tbody").html(orderHtml);
          } else {
            /*
            if (payType) {
              res.order_detail = res.order_detail.filter(function (m) {
                //  m.pay_method.indexOf(payType)>-1
                m.pay_method = m.pay_method.filter(function (p) {
                  return p.pay_method == payType
                })
                return m.pay_method.length > 0
              })
            }
            */
            fillData(res, orderHtml);
          }
        } else {
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    }

  }

  function fillData(res, orderHtml) {

    if (res.order_detail.length == 0) {
      orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
    } else {

      $.each(res.order_detail, function (i, v) {
        // if(v.pay_method.length==0){
        //   orderHtml="<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据 11      ! ! !</td></tr>"
        // }else{
        orderHtml += "<tr data-orderinfo='" + JSON.stringify(v) + "'>";
        orderHtml += "<td>" + v.sequence + "</td>";
        orderHtml += "<td>" + v.order_sequence + "</td>";
        orderHtml += "<td>" + v.order_id + "</td>";
        orderHtml += "<td>" + v.floor + "</td>";
        orderHtml += "<td>" + v.taihao + "</td>";
        orderHtml += "<td>" + v.total_pay + "</td>";
        orderHtml += "<td>";
        $.each(v.pay_method, function (j, k) {
          orderHtml += "<p>" + k.pay_method + ":" + k.money + "</p>";
        })
        orderHtml += "</td>";
        orderHtml += "<td>" + v.time + "</td>";
        orderHtml += "<td>" + v.pay_state + "</td>";
        orderHtml += "<td><button class='check' data-toggle='modal' data-target='#BillModal'>查看</button></td>";
        orderHtml += "</tr>";
      })
    }
    $(".orderForm .tableData tbody").html(orderHtml);
    // $(".orderForm .tableData tbody").append(orderHtml);
  }

  //分页
  function pagination_orders(pageAllNum){
    App.ajax("ss_wx/order_details", "post", {
      state: state,
      check_state: check_state,
      payType: payType,
      page: pageAllNum
    }, function (res) {
      if (res.flag == true) {
        pageAllTotal = res.pageAllTotal;
        // totalData = res.totalData;
        var orderHtml = "";
        if (res.order_detail.length == 0) {
          orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
          $(".orderForm .tableData tbody").html(orderHtml);
        } else {
          if (payType) {
            res.order_detail = res.order_detail.filter(function (m) {
              m.pay_method = m.pay_method.filter(function (p) {
                return p.pay_method == payType
              })
              return m.pay_method.length > 0
            })
          }
          fillData(res, orderHtml);
        }
      } else {
        App.msg(res.msg);
      }
      if (!res.TokenTrue) {
        App.msg("Token失效，即将跳转到登录页面", function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })
  }

  function pagination_refund_orders(pageAllNum){
    App.ajax("ss_wx/pos_refund_details", "post", {
      page: pageAllNum
    }, function (res) {
      if (res.flag == true) {
        pageAllTotal = res.pageAllTotal;
        var orderHtml = "";
        if (res.order_detail.length == 0) {
          orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
          $(".orderForm .tableData tbody").html(orderHtml);
        } else {
          if (payType) {
            res.order_detail = res.order_detail.filter(function (m) {
              m.pay_method = m.pay_method.filter(function (p) {
                return p.pay_method == payType
              })
              return m.pay_method.length > 0
            })
          }
          fillData(res, orderHtml);
        }
      } else {
        App.msg(res.msg);
      }
      if (!res.TokenTrue) {
        App.msg("Token失效，即将跳转到登录页面", function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })
  }

  //汇总打印
  function date(idName, datFmt, maxId, minId) {
    $("#" + idName).off("click").on("click", function () {
      WdatePicker({
        $wdate: false,
        dateFmt: datFmt,
        el: idName,
        skin: 'twoer',
        maxDate: maxId ? '#F{$dp.$D(\'' + maxId + '\')}' : "",
        minDate: minId ? '#F{$dp.$D(\'' + minId + '\')}' : "",
        onpicked: function () {}
      });
    });
  }
  date("Time", "yyyy-MM-dd HH:mm", 'Time1', '');
  date("Time1", "yyyy-MM-dd HH:mm", '', 'Time');
  //点击汇总打印弹框确定
  $("#printModal .btnSure").off("click").on("click", function () {
    var Time = $("#Time").val();
    var Time1 = $("#Time1").val();
    if (Time == "" || Time1 == "") {
      App.msg("请选择时间");
    } else {
      App.ajax("ss_wx/SaleSummyPrinte", "post", {
        start_date: Time,
        end_date: Time1
      }, function (res) {
        $("#Time").val("");
        $("#Time1").val("");
        if (res.flag == true) {
          App.msg("打印中...");
          $("#printModal").modal("hide");
          window.samfeng.Collection(JSON.stringify(res), Time, Time1);
          location.reload();
        } else {
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    }
  })
  //点击查看
  $(".orderForm .tableData").on("click", ".check", function () {
    var state = $(".orderForm .main_content_top li.active").data("state");
    var orderInfo = $(this).parents("tr").data("orderinfo");
    let order_refund = orderInfo.order_refund;
    if (orderInfo.pay_state == "已支付") {
      if (!order_refund){
        $("#BillModal .FJZ,#BillModal .REFUND").addClass("hidden");
      } else {
        $("#BillModal .FJZ,#BillModal .REFUND").removeClass("hidden");
      }
      // $("#BillModal .DZD").removeClass("hidden");
      $("#BillModal .CC,#BillModal .CFCT,#BillModal .QZF").addClass("hidden");
    } else if (orderInfo.pay_state == "未结账") {
      $("#BillModal .CC,#BillModal .CFCT,#BillModal .DZD,#BillModal .QZF").removeClass("hidden");
      $("#BillModal .FJZ").addClass("hidden");
      $("#BillModal .REFUND").addClass("hidden");
    } else if (orderInfo.pay_state == "已退款") {
      $("#BillModal .CC,#BillModal .CFCT,#BillModal .FJZ,#BillModal .QZF,#BillModal .REFUND").addClass("hidden");
      $("#BillModal .DZD").removeClass("hidden");
    } else {
      $("#BillModal .modal-footer .btn").addClass("hidden");
    }
    var orderHtml = "";
    var headHtml = "";
    var menuHtml = "";
    orderHtml += "<div class='billItem'><span>桌台号：</span><span>" + orderInfo.taihao + "</span></div>"
    orderHtml += "<div class='billItem'><span>排队号：</span><span>" + orderInfo.order_sequence + "</span></div>"
    orderHtml += "<div class='billItem'> <span>订单编号：</span> <span>" + orderInfo.order_id + "</span></div>";
    orderHtml += "<div class='billItem'> <span>移动支付订单号：</span> <span>"+orderInfo.koudai_order+"</span></div>";
    orderHtml += "<div class='billItem'> <span>支付方式：</span> <span>";
    $.each(orderInfo.pay_method, function (i, v) {
      orderHtml += v.pay_method + ",";
    })
    orderHtml += "</span></div>";
    if (state != 6) {
      orderHtml += "<div class='billItem'> <span>用餐人数：</span> <span>" + orderInfo.has_seat + "</span></div>";
    }
    orderHtml += "<div class='billItem'> <span>订单金额：</span> <span class='red'>" + orderInfo.total_pay + "</span></div>";
    orderHtml += "<div class='billItem'> <span>优惠金额：</span> <span class='red'>" + orderInfo.total_discount + "</span></div>";
    orderHtml += "<div class='billItem red'> <span>备注信息：</span> <span>" + orderInfo.note + "</span></div>";
    orderHtml += "<div class='billItem red'> <span>收银备注信息：</span> <span>" + orderInfo.pay_note + "</span></div>";
    $("#BillModal .modal-body .left").html(orderHtml);
    headHtml += '<span>商品名称</span><span>单价(元)</span>';
    if (state == 6) {
      headHtml += '<span>原数量</span><span>退菜数量</span>'
    } else {
      headHtml += '<span>数量</span>';
      headHtml += '<span>金额(元)</span>';
    }
    $("#BillModal .right .tit").html(headHtml);
    $.each(orderInfo.order_lines, function (i, v) {
      var price = v.price==0?0:(v.price||v.p_price);
      var current_price = parseFloat(price).toFixed(2);
      var current_total_price = (price * v.num).toFixed(2);
      var ZF_name="";
      if(v.cuisine && v.cuisine.length>0){
        v.cuisine.forEach(function(m,n){
          ZF_name+=m.name+" ";
        })
      }
      menuHtml += "<li data-dishes=\'" + JSON.stringify(v) + "\' class='" + (v.refund_qty > 0 ? "red" : "") + "'>" +
          "<span>" + (v.name||v.p_name) + (v.cuisine && v.cuisine.length > 0 ? "<span style='color:#f40'> | " + ZF_name+"" +
              "</span>" : (v.combo_details && v.combo_details.length > 0 ? "" +
              "<a style='margin-left:8px;' class='btn btn-details btn-warning btn-sm' data-toggle='popover'>" +
              "套餐详情</a>" : "")) + "</span><span>" + current_price  + "</span>";
      if (state == 6) {
        menuHtml += "<span>" + v.origin_qty + "</span><span>" + v.refund_qty + "</span>"
      } else {
        menuHtml += "<span>" + v.num + "</span>";
        menuHtml += "<span>" + current_total_price + "</span></li>";
      }
    })
    $("#BillModal .dishLists").html(menuHtml);
    //点击套餐详情
    $("#BillModal .dishLists").off("mouseover").on("mouseover", ".btn-details", function () {
      var dishes = $(this).parents("li").data("dishes");
      var content = "";
      var menu_list = [];
      dishes.combo_details.forEach(function (x, y) {
        x.menu_list.forEach(function (a, b) {
          menu_list.push(a);
        })
      })
      menu_list.forEach(function (a, b) {
        content += b + 1 + "." + a.name + '---' + a.select_num + a.uom + '---' + a.price + '元/' + a.uom + "<br/>"
      })
      $(this).popover({
        content: content,
        placement: "left",
        trigger: "click",
        html: true
      })
    });

    //点击查询移动订单号
    $("#BillModal .CHECKPAY").off("click").on("click", function () {
      App.confirm("确定查询？", function () {
          $('#loading').modal('show');
          $('#BillModal').modal('hide');
          App.ajax("ss_wx/CheckPayState", "post", {
              "koudai_order": orderInfo.koudai_order,
              "order_id": orderInfo.order_id
          }, function (res) {
              if (res.flag == true) {
                  App.msg(res.msg, function () {
                      setTimeout(function () {
                          $('#loading').modal('hide');
                          location.reload();
                      }, 1000);
                  })
              } else {
                  $('#loading').modal('hide');
                  App.msg(res.msg);
              }
              if (!res.TokenTrue) {
                  App.msg("Token失效，即将跳转到登录页面", function () {
                      setTimeout(function () {
                          location.href = "../login.html";
                      }, 1000)
                  })
              }
          })
      })

    });

    //点击翻台
    $("#BillModal .FJZ").off("click").on("click", function () {
      App.confirm("确定翻台？", function () {
        $('#loading').modal('show');
        $('#BillModal').modal('hide');
        App.ajax("ss_wx/hzg_pos_refund", "post", {
          "refund_order_id": orderInfo.sequence,
          "refund": false
        }, function (res) {
          if (res.flag == true) {
            App.msg("翻台成功,请到桌台页面进行订单修改", function () {
              setTimeout(function () {
                $('#loading').modal('hide');
                location.reload();
              }, 1000);
            })
          } else {
            $('#loading').modal('hide');
            App.msg(res.msg);
          }
          if (!res.TokenTrue) {
            App.msg("Token失效，即将跳转到登录页面", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      })

    });

    /*
    //点击删除订单
    $("#BillModal .DELETEORDER").off("click").on("click", function () {
      App.confirm("确定删除订单？", function () {
        $('#loading').modal('show');
        $('#BillModal').modal('hide');
        App.ajax("delete/false/pay/order", "post", {
          "order_id": orderInfo.sequence
        }, function (res) {
          if (res.flag == true) {
            App.msg("删除成功", function () {
              setTimeout(function () {
                $('#loading').modal('hide');
                location.reload();
              }, 1000);
            })
          } else {
            $('#loading').modal('hide');
            App.msg(res.msg);
          }
          if (!res.TokenTrue) {
            App.msg("Token失效，即将跳转到登录页面", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      })

    });
    */

    //点击退款
    $("#BillModal .REFUND").off("click").on("click", function () {
      App.confirm("确定退款？", function () {
        $('#loading').modal('show');
        $('#BillModal').modal('hide');
        App.ajax("ss_wx/hzg_pos_refund", "post", {
          "refund_order_id": orderInfo.sequence,
          "refund": true
        }, function (res) {
          if (res.flag == true) {
            App.msg("退款成功", function () {
              setTimeout(function () {
                $('#loading').modal('hide');
                location.reload();
              }, 1000);
            })
          } else {
            $('#loading').modal('hide');
            App.msg(res.msg);
          }
          if (!res.TokenTrue) {
            App.msg("Token失效，即将跳转到登录页面", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      })

    });

    //点击对账单
    $("#BillModal .DZD").off("click").on("click", function () {
      App.ajax("ss_wx/order_print", 'post', {
        order_id: orderInfo.sequence
      }, function (res) {
        if (res.flag == true) {
          App.msg("打印中...", function () {
            setTimeout(function () {
              location.reload();
            }, 1000);
          });
          window.samfeng.HistoryOrder(JSON.stringify(res.pos_order));
        } else {
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    });
    //点击去支付
    $("#BillModal .QZF").off("click").on("click", function () {
      location.href = "Cashier_1.html?pay_tableid=" + orderInfo.table_id;
    })
  });

    $(".loadclose").off("click").on("click", function (){
        $('#loading').modal('hide');
    });


    //选择订单的不同状态
  $(".orderForm .main_content_top").on("click", "li", function () {
    $(this).addClass("active").siblings().removeClass("active");
    state = $(this).data("state");
    check_state = $(".checkType select").val();
    getOrderDetails(state, check_state, payType);
  })
  //切换查询状态
  $(".checkType select").on("change", function () {
    check_state = $(this).val();
    payType = $(".payList select").val();
    if (payType == "all") {
      payType = "";
    }
    var state = $(".orderForm .main_content_top li.active").data("state");
    getOrderDetails(state, check_state, payType);
  })

  //选择支付方式
  $(".payList select").on("change", function () {
    payType = $(this).val();
    // var pt = $(this).data("paytype");
    // console.log(pt);
    // console.log(pt.code);
    if (payType == "all") {
      payType = "";
    }
    var state = $(".orderForm .main_content_top li.active").data("state");
    check_state = $(".checkType select").val();
    getOrderDetails(state, check_state, payType);
  })
  //点击搜索
  $(".orderForm .Search").off("click").on("click", function () {
    payType = $(".payList select").val();
    if (payType == "all") {
      payType = "";
    }
    state = $(".orderForm .main_content_top li.active").data("state");
    check_state = $(".checkType select").val();
    getOrderDetails(state, check_state, payType);
  })

  //搜索输入框查询
  $("#searInput").off("click").on("click", function () {
    var searVal = $("#searVal").val();
    payType = $(".payList select").val();
    if (payType == "all") {
      payType = "";
    }
    state = $(".orderForm .main_content_top li.active").data("state");
    check_state = $(".checkType select").val();
    if (searVal == "") {
      return;
    } else {
      App.ajax("ss_wx/search_order_details", "post", {
        search_str: searVal
      }, function (res) {
        // console.log(res);
        if (res.flag == true) {
          $(".main_content_top li").first().addClass("active").siblings().removeClass("active");
          var orderHtml = "";
          if (res.order_detail.length == 0) {
            orderHtml = "<tr><td colspan='30' style='font-size:16px;font-weight:600;'>未 查 询 到 数 据  ! ! !</td></tr>";
            $(".orderForm .tableData tbody").html(orderHtml);
          } else {
            fillData(res, orderHtml);
          }
          $("#searVal").val("");
        } else {
          App.msg(res.msg);
        }
        if (!res.TokenTrue) {
          App.msg("Token失效，即将跳转到登录页面", function () {
            setTimeout(function () {
              location.href = "../login.html";
            }, 1000)
          })
        }
      })
    }
  });

  //点击交班
  App.jiaoBan()

})